package cn.cxyxj.study.webflux03;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.HashMap;

/**
 * 认证失败回调
 *
 * @author cxyxj
 */
@Component
public class CustomAuthenticationFailHandler implements ServerAuthenticationFailureHandler {

    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException e) {
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);
        response.getHeaders().add("Content-Type", "application/json; charset=UTF-8");
        String msg = "";
        if (e instanceof LockedException) {
            msg = "账户被锁定，请联系管理员!";
        } else if (e instanceof BadCredentialsException) {
            msg = "用户名或者密码输入错误，请重新输入!";
        } else {
            msg = e.getMessage();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("code", "99999");
        map.put("message", msg);
        ObjectMapper objectMapper = new ObjectMapper();
        DataBuffer dataBuffer = null;
        try {
            dataBuffer = response.bufferFactory().wrap(objectMapper.writeValueAsBytes(map));
        } catch (JsonProcessingException jsonProcessingException) {
            jsonProcessingException.printStackTrace();
        }
        return response.writeWith(Mono.just(dataBuffer));
    }
}